<script setup lang="ts">
import CustomNavbar from '@/pages/index/components/CustomNavbar.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue'
import HotPanel from '@/pages/index/components/HotPanel.vue'
import type { MonkeyGuessInstance } from '@/types/component'
import pageSkeleton from '@/pages/index/components/pageSkeleton.vue'
import { useGuessList } from '@/composables/index'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
// 获取分类数据
const categoryList = ref<CategoryItem[]>([])
const getCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}
// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

// 滚动触底时调用
// const guessRef = ref<MonkeyGuessInstance>()
// const onScrolltolower = () => {
//   guessRef.value.getMoreguessData()
// }
// 调用猜你喜欢组合式函数
const { guessRef, onScrolltolower } = useGuessList()

// 下拉刷新调用
const isTriggerd = ref(false)
const onRefresherEnabled = async () => {
  // 猜你喜欢重置数据
  guessRef?.value.resetData()
  isTriggerd.value = true
  await Promise.all([
    getHomeBannerData(),
    getCategoryData(),
    getHotData(),
    guessRef.value?.getMoreguessData(),
  ])
  isTriggerd.value = false
}

// 是否在加载数据标志
const isLoading = ref(false)

// 页面加载时调用
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getCategoryData(), getHotData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 导航栏组件 -->
  <CustomNavbar />
  <scroll-view
    scroll-y
    @scrolltolower="onScrolltolower"
    refresher-enabled
    @refresherrefresh="onRefresherEnabled"
    :refresher-triggered="isTriggerd"
  >
    <!-- 骨架屏 -->
    <pageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播组件 -->
      <MonkeySwiper :list="bannerList" />
      <!-- 分类组件 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门组件 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢组件 -->
      <MonkeyGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

scroll-view {
  flex: 1;
}
</style>
